<template>
  <PageMain>
    <ProTable ref="tableRef" :columns="columns" :init-param="initParam" :request-api="getTableList" border @darg-sort="sortTable">
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="warning" link @click="resetPwdFn(scope.row)">重置密码</el-button>
        <el-button type="warning" link @click="enableFn(scope.row)">{{ scope.row.state ? "禁用" : "启用" }}</el-button>
      </template>
    </ProTable>
  </PageMain>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { useHandleData } from "@/hooks/useHandleData";
import api from "@/api";

const router = useRouter();
const rowData = ref();
const tableRef = ref();
// 表格初始参数
const initParam = reactive({
  pageNum: 1,
  pageSize: 10,
});

const getTableList = (params) => {
  if (params.timekey?.length > 1) {
    params.startCreateTime = params.timekey[0];
    params.endCreateTime = params.timekey[1];
  }
  return api.post(`/userOperateLog/queryPage`, params, {
    loading: true,
  });
};

// 表格配置项
const columns = ref([
  { label: "账号", prop: "userAccount", align: "left", search: { el: "input", showLabel: true } },
  {
    label: "操作时间",
    prop: "createTime",
    align: "left",
    search: {
      el: "date-picker",
      span: 2,
      key: "timekey",
      showLabel: true,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
    },
  },
  { label: "操作", prop: "operateDesc", align: "left" },
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }) => {
  console.log(newIndex, oldIndex);
  console.log(tableRef.value?.tableData);
  ElMessage.success("修改列表排序成功");
};

// 更新数据
const updata = () => {
  tableRef.value.getTableList();
};

// 新增用户
const addRef = ref();
const addFn = (title, row) => {
  addRef.value.show(title, row);
};

// 编辑用户信息
const editFn = (row) => {
  router.push({
    path: "/users/edit",
    query: { id: row.id },
  });
};

// 查看详情
const detailFn = (row) => {
  router.push({
    path: "/users/detail",
    query: { id: row.id },
  });
};

// 删除
const enableFn = async (row) => {
  const text = row.state ? "禁用" : "启用";
  await useHandleData(deleteApi, {}, `${text}【${row.userName}】`);
  row.state = !row.state;
  // tableRef.value.getTableList();
};
const deleteApi = () => {
  if (!rowData.value) return;
  return api.delete(`/org/${rowData.value.userId}`);
};

// 重置密码
const resetPwdFn = async (row) => {
  await useHandleData(resetPwdApi, { userId: row.userId }, `重置【${row.nickName}】密码`);
  tableRef.value.getData();
};
const resetPwdApi = () => {
  return api.put(`/user/resetPwd`);
};
</script>
